import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import Login from '@/views/login/index.vue';
import Register from '@/views/register/index.vue';
import Home from '@/views/Home.vue';
import Curvefit from '@/views/matlab/plugins/Curvefit.vue';

// 导入所有路由
const allComponents = require.context('./modules/', false, /^.*\.js$/);
const res_components = [];
allComponents.keys().forEach(fileName => {
  if (fileName !== './index.js') {
    const comp = allComponents(fileName);
    res_components.push(...comp.default);
  }
});

const routes = [
  {
    path: '/Curvefit',
    name: 'Curvefit',
    component: Curvefit
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  // TODO 这路由配置得 感觉怪怪的
  {
    path: '/',
    component: Home,
    children: [
      ...res_components
    ]
  },
  {
    path: '*',
    redirect: { name: 'Home' }
  }
];

// TODO hash的路由模式感觉不是很好
const router = new VueRouter({
  routes
});

// 获取原型对象上的push函数
const originalPush = VueRouter.prototype.push;

// 修改原型对象中的push方法，捕捉错误
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};

router.beforeEach((to, from, next) => {
  // 登录和注册页面直接放行
  if (to.path === '/login' || to.path === '/register') return next();

  // 没有用户信息或token 跳转到登录界面
  const res = localStorage.getItem('kaitian_user');
  if (!res) {
    next({
      path: '/login',
      // TODO 可是这样会导致url不干净欸
      query: { redirect: to.fullPath }
    });
  }
  // TODO 感觉校验上面一个就够了 毕竟是一起的
  const tt = JSON.parse(res);
  const token = tt.token;
  if (!token || token === '{}' || !token.token || !token.lastTime) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    });
  }

  // TODO token不应该由后端校验吗？

  // 守卫审核界面
  if (to.path === '/examine') {
    // TODO 呃呃
    if (tt.uid !== 23) {
      next({
        path: '/'
      });
    }
  }
  next();
});

export default router;
